﻿using NLog.Web;
using WomanMotion.WebApi.Api.Controllers;
using WomanMotion.WebApi.Infrastructure.UnifyResult;
using System.Text.Json.Serialization;
using System.Text.Json;
using LogDashboard.Extensions;
using Microsoft.AspNetCore.Http;

namespace WomanMotion.WebApi.Api.Utility
{
    /// <summary>
    /// 自定义全局异常中间件
    /// </summary>
    public class GlobalExceptionMiddleware
    {
        private readonly ILogger<GlobalExceptionMiddleware> _logger;
        private readonly RequestDelegate _next;

        public GlobalExceptionMiddleware(RequestDelegate next , ILogger<GlobalExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception exception)
            {
                // 你可以在这里进行相关的日志记录
                _logger.LogError("异常请求类型:" + context.Request.Method + "  异常请求路径:" + context.Request.Path);
                _logger.LogError(exception.ToString());
                await HandleExceptionAsync(context, exception);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            // 返回信息格式
            context.Response.ContentType = "application/json";
            // 返回的Http 状态码
            context.Response.StatusCode = 500;
            //返回的消息内容
            var responseModel = ResultOutput.NotOk("服务器出现异常，异常时间:" + DateTime.Now.ToString() + " 请联系管理员处理。");
            //返回消息
            await context.Response.WriteAsync(JsonSerializer.Serialize(responseModel));
            //await context.Response.WriteAsync(responseModel.ToJsonString());
        }
    }
}
